package com.sc.nft.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.sc.nft.dao.MarketManagementDaoPoolDao;
import com.sc.nft.entity.MarketManagementDaoPool;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.MarketManagementDaoPoolService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;

/**
 * 市值管理结算池
 *
 * @Author：LiGen
 * @Package：com.sc.nft.service.impl
 * @Project：sc_metago
 * @name：MarketManagementDaoPoolServiceImpl
 * @Date：2024/7/24 13:48
 * @Filename：MarketManagementDaoPoolServiceImpl
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MarketManagementDaoPoolServiceImpl implements MarketManagementDaoPoolService {

    private final MarketManagementDaoPoolDao marketManagementDaoPoolDao;

    /**
     * 添加池中金额
     *
     * @param ecologyHatchId
     * @param collectionId
     * @param daoId
     * @param amount
     * @return
     */
    @Override
    public Long addAmount(Long ecologyHatchId, Long collectionId, Long daoId, BigDecimal amount, Date now) {
        // 获取当前月的市值管理池
        MarketManagementDaoPool marketManagementDaoPool = marketManagementDaoPoolDao.getOneByEcologyHatchId(ecologyHatchId, collectionId, daoId, now);
        if (Objects.isNull(marketManagementDaoPool)) {
            DateTime beginOfMonth = DateUtil.beginOfMonth(now);
            DateTime endOfMonth = DateUtil.endOfMonth(now).offsetNew(DateField.SECOND, -1);
            marketManagementDaoPool = new MarketManagementDaoPool();
            marketManagementDaoPool.setEcologyHatchId(ecologyHatchId);
            marketManagementDaoPool.setCollectionId(collectionId);
            marketManagementDaoPool.setDaoId(daoId);
            marketManagementDaoPool.setAmount(BigDecimal.ZERO);
            marketManagementDaoPool.setStartTime(beginOfMonth);
            marketManagementDaoPool.setEndTime(endOfMonth);
            marketManagementDaoPool.setIsSettle(Boolean.FALSE);
            marketManagementDaoPool.insert();
        }
        if (marketManagementDaoPool.getIsSettle()) {
            // 已结算
            throw new GlobalRunTimeException("市值管理结算池已结算");
        }
        // 添加金额
        marketManagementDaoPoolDao.addAmount(marketManagementDaoPool.getId(), amount);
        return marketManagementDaoPool.getId();
    }
}
